package com.titar.robot.widgets;

import android.content.Context;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

/**
 * Created by zhangdk on 2017/6/12.
 */

public class CountdownTextView extends AppCompatTextView implements View.OnClickListener {
    /**
     * 倒计时长，默认60秒
     */
    private int length = 60 * 1000;
    /**
     * 当前倒计时时间
     */
    private int currentLength;
    /**
     * 倒计时的Timer
     */
    private MyCountdownTimer mTimer;
    /**
     * 一开始显示的文字
     */
    private String beforeText = "获取验证码";
    /**
     * 倒计时单位显示
     */
    private String afterText = "s";
    /**
     * 按钮点击事件监听
     */
    private View.OnClickListener onClickListener;


    public CountdownTextView(Context context) {
        this(context, null);
    }

    public CountdownTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CountdownTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        if (!TextUtils.isEmpty(getText())) {
            beforeText = getText().toString().trim();
        }
        this.setText(beforeText);
        setOnClickListener(this);
        currentLength = length;
    }

    /**
     * 设置倒计时时长，单位毫秒
     * @param length
     */
    public void setCountdownLength(int length) {
        this.length = length;
        currentLength = length;
    }

    /**
     * 设置未点击前显示的文字
     * @param beforeText
     */
    public void setBeforeText(String beforeText) {
        this.beforeText = beforeText;
    }

    @Override
    public void setOnClickListener(@Nullable View.OnClickListener l) {
        if (l instanceof CountdownTextView)
            super.setOnClickListener(l);
        else
            this.onClickListener = l;
    }

    @Override
    public void onClick(View v) {
        startCountdown();
        if (onClickListener != null)
            onClickListener.onClick(v);
    }

    private void startCountdown() {
        mTimer = new MyCountdownTimer(length + 50, 1000);
        mTimer.start();
        this.setText(currentLength / 1000 + afterText);
        this.setEnabled(false);
    }

    public void reset() {
        CountdownTextView.this.setText(beforeText);
        CountdownTextView.this.setEnabled(true);
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        currentLength = length;

    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mTimer != null)
            mTimer.cancel();
    }

    private static final int MSG_TICK = 1;
    private static final int MSG_FINISH = 2;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_TICK) {
                CountdownTextView.this.setText(currentLength / 1000 + afterText);
                currentLength -= 1000;
                if (currentLength < 0) {
                    reset();
                }
            } else {
                reset();
            }
        }
    };

    class MyCountdownTimer extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public MyCountdownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mHandler.sendEmptyMessage(MSG_TICK);
        }

        @Override
        public void onFinish() {
            mHandler.sendEmptyMessage(MSG_FINISH);
        }
    }

}
